package com.grad.webstudy.service.impl;

import com.grad.webstudy.dao.AuthorityDao;
import com.grad.webstudy.model.Authority;
import com.grad.webstudy.service.AuthorityService;
import com.grad.webstudy.vo.AuthVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @Description:
 * @Author: zjf
 * @Date: 2020/1/20 14:06.
 */
@Service
public class AuthorityServiceImpl implements AuthorityService {

    @Autowired
    private AuthorityDao authorityDao;

    @Override
    public List<String> queryAuthDeatilByIds(Set<String> authIds) {
        if (authIds.size() <= 0) {
            System.out.println("普通用户");
            return new ArrayList<>();
        }
        return authorityDao.queryAuthDeatilByIds(authIds);
    }

    @Override
    public List<AuthVo> queryAll() {
        List<Authority> authorities = authorityDao.queryAllAuth();

        List<AuthVo> result = transToVo(authorities);
        return result;
    }

    private List<AuthVo> transToVo(List<Authority> authorities) {
        List<AuthVo> result = new ArrayList<>();
        List<AuthVo> authVoList = new ArrayList<>();


        //获取一级权限
        for (Authority authority : authorities) {
            AuthVo authVo = new AuthVo.Builder()
                    .setId(authority.getId())
                    .setAuth(authority.getAuth())
                    .setAuthDesc(authority.getAuthDesc())
                    .setParentId(authority.getParentId())
                    .setChildren(new ArrayList<>())
                    .build();
            authVoList.add(authVo);//将实体类转换为VO


            if (authority.getParentId() == 0) {

                AuthVo authVo1 = new AuthVo.Builder()
                        .setId(authority.getId())
                        .setAuth(authority.getAuth())
                        .setAuthDesc(authority.getAuthDesc())
                        .setParentId(authority.getParentId())
                        .setChildren(new ArrayList<>())
                        .build();
                result.add(authVo1);

            }
        }


        //获取子节点
        for (AuthVo authVo : result) {
            authVo = recursiveTree(authVo, authVoList);
        }


        return result;
    }


    /**
     * 递归构造子节点
     *
     * @param authVo
     * @param authorities
     * @return
     */
    private AuthVo recursiveTree(AuthVo authVo, List<AuthVo> authorities) {
        for (AuthVo authority : authorities) {
            if (authority.getParentId() == authVo.getId()) {
                authority = recursiveTree(authority, authorities);
                authVo.getChildren().add(authority);
                authVo.setHasChild(true);
            }
        }
        return authVo;
    }

}
